package com.lovesoft.prologer.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
import java.util.TreeMap;

/**
 * Can load and save some stuff in map (freeze and unfreeze)
 * @author Patryk Kaluzny
 * @param <K>
 * @param <V>
 */
public class Freezer<K extends Serializable ,V extends Serializable> {
	private String fileName;

	public Freezer(String fileName) {
		super();
		this.fileName = fileName;
	}

	@SuppressWarnings("unchecked")
	public Map<K, V> defrost() throws IOException {
		File file = new File(fileName);
		FileInputStream fis = new FileInputStream(file);
		ObjectInputStream ois = new ObjectInputStream(fis);
		TreeMap<K,V> food;
		try {
			food = (TreeMap<K,V>) ois.readObject();
			ois.close();
		} catch (Exception e) {
			ois.close();
			throw new IOException("Upsss",e);
		}
		return food;
	}

	public void freeze(Map<K, V> food) throws IOException {
		File file = new File(fileName);
		if(!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(file);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(food);
		oos.close();
	}
}
